import { useState, useEffect } from 'react';
import { Toast, Dialog } from 'antd-mobile';
import { MinusOutline, AddOutline } from 'antd-mobile-icons';
import styles from './Cars.module.css';

// 购物车商品类型
interface CartItem {
  id: string;
  title: string;
  image: string;
  currentPrice: number;
  originalPrice: number;
  quantity: number;
  category: string;
  tags?: string[];
  activity?: string[];
  stock: number;
  selected: boolean;
}

export default function Cars() {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [isEditMode, setIsEditMode] = useState(false);

  // 从 localStorage 加载购物车数据
  useEffect(() => {
    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
      try {
        const parsedCart = JSON.parse(savedCart);
        setCartItems(parsedCart);
      } catch (error) {
        console.error('解析购物车数据失败:', error);
        setCartItems([]);
      }
    }
  }, []);

  // 保存购物车数据到 localStorage
  const saveCartToStorage = (items: CartItem[]) => {
    localStorage.setItem('cart', JSON.stringify(items));
  };

  // 更新购物车
  const updateCart = (newItems: CartItem[]) => {
    setCartItems(newItems);
    saveCartToStorage(newItems);
  };

  // 计算总价
  const calculateTotal = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((total, item) => total + (item.currentPrice * item.quantity), 0);
  };

  // 计算节省金额
  const calculateSaved = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((total, item) => total + ((item.originalPrice - item.currentPrice) * item.quantity), 0);
  };

  // 计算选中商品数量
  const selectedCount = () => {
    return cartItems.filter(item => item.selected).length;
  };

  // 切换商品选中状态
  const toggleItemSelection = (itemId: string) => {
    const updatedItems = cartItems.map(item =>
      item.id === itemId ? { ...item, selected: !item.selected } : item
    );
    updateCart(updatedItems);
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    const currentStatus = getSelectAllStatus();
    
    // 如果当前是全选状态，则取消全选
    // 如果当前是部分选中或全不选状态，则全选
    const newSelectAll = currentStatus !== true;
    const updatedItems = cartItems.map(item => ({ ...item, selected: newSelectAll }));
    updateCart(updatedItems);
  };

  // 获取全选状态
  const getSelectAllStatus = () => {
    if (cartItems.length === 0) return false;
    
    const allSelected = cartItems.every(item => item.selected);
    const someSelected = cartItems.some(item => item.selected);
    
    if (allSelected) return true;
    if (someSelected) return 'indeterminate'; // 部分选中
    return false; // 全不选
  };

  // 增加商品数量
  const increaseQuantity = (itemId: string) => {
    const updatedItems = cartItems.map(item => {
      if (item.id === itemId && item.quantity < item.stock) {
        return { ...item, quantity: item.quantity + 1 };
      }
      return item;
    });
    updateCart(updatedItems);
  };

  // 减少商品数量
  const decreaseQuantity = (itemId: string) => {
    const updatedItems = cartItems.map(item => {
      if (item.id === itemId && item.quantity > 1) {
        return { ...item, quantity: item.quantity - 1 };
      }
      return item;
    });
    updateCart(updatedItems);
  };

  // 批量删除
  const deleteSelected = async () => {
    const selectedItems = cartItems.filter(item => item.selected);
    if (selectedItems.length === 0) {
      Toast.show('请先选择要删除的商品');
      return;
    }

    const result = await Dialog.confirm({
      content: `确定要删除选中的 ${selectedItems.length} 个商品吗？`,
    });

    if (result) {
      const updatedItems = cartItems.filter(item => !item.selected);
      updateCart(updatedItems);
      Toast.show('商品已删除');
    }
  };

  // 去结算
  const goToCheckout = () => {
    const selectedItems = cartItems.filter(item => item.selected);
    if (selectedItems.length === 0) {
      Toast.show('请先选择要结算的商品');
      return;
    }
    
    // 这里可以跳转到结算页面
    Toast.show('跳转到结算页面');
  };

  // 渲染商品标签
  const renderTags = (item: CartItem) => {
    if (!item.tags || item.tags.length === 0) return null;
    
    return (
      <div className={styles.tags}>
        {item.tags.map((tag, index) => (
          <span key={index} className={styles.tag}>{tag}</span>
        ))}
      </div>
    );
  };

  // 渲染活动标签
  const renderActivity = (item: CartItem) => {
    if (!item.activity || item.activity.length === 0) return null;
    
    return (
      <div className={styles.activity}>
        {item.activity.map((activity, index) => (
          <span key={index} className={styles.activityTag}>
            {activity === '限时秒杀' ? '秒杀' : activity === '特惠拼团' ? '拼团' : activity}
          </span>
        ))}
      </div>
    );
  };

  return (
    <div className={styles.cartContainer}>
      {/* 顶部栏 */}
      <div className={styles.header}>
        <span className={styles.title}>购物车</span>
        <span 
          className={styles.edit} 
          onClick={() => setIsEditMode(!isEditMode)}
        >
          {isEditMode ? '完成' : '编辑'}
        </span>
      </div>

      {/* 自提点 */}
      <div className={styles.pickup}>自提点：万达广场店</div>

      {/* 商品列表 */}
      <div className={styles.cartList}>
        {cartItems.length === 0 ? (
          <div className={styles.emptyCart}>
            <div className={styles.emptyIcon}>🛒</div>
            <div className={styles.emptyText}>购物车是空的</div>
            <div className={styles.emptyTip}>快去添加一些商品吧</div>
          </div>
        ) : (
          cartItems.map(item => (
            <div key={item.id} className={styles.cartItem}>
              {/* 活动标签 */}
              {item.activity && item.activity.length > 0 && (
                <div className={styles.itemHeader}>
                  {renderActivity(item)}
                </div>
              )}
              
              <div className={styles.itemBody}>
                <input 
                  type="checkbox" 
                  checked={item.selected}
                  onChange={() => toggleItemSelection(item.id)}
                  className={styles.checkbox} 
                />
                
                <div className={styles.imgBox}>
                  <img src={item.image} alt={item.title} className={styles.productImage} />
                </div>
                
                <div className={styles.info}>
                  <div className={styles.name}>{item.title}</div>
                  {renderTags(item)}
                  <div className={styles.limit}>限购{item.stock}件</div>
                  <div className={styles.priceRow}>
                    <span className={styles.price}>¥{item.currentPrice}</span>
                    <span className={styles.oldPrice}>¥{item.originalPrice}</span>
                  </div>
                </div>
                
                <div className={styles.countBox}>
                  <button 
                    className={styles.countBtn}
                    onClick={() => decreaseQuantity(item.id)}
                    disabled={item.quantity <= 1}
                  >
                    <MinusOutline />
                  </button>
                  <span className={styles.count}>{item.quantity}</span>
                  <button 
                    className={styles.countBtn}
                    onClick={() => increaseQuantity(item.id)}
                    disabled={item.quantity >= item.stock}
                  >
                    <AddOutline />
                  </button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 底部栏 */}
      {cartItems.length > 0 && (
        <div className={styles.footer}>
          <div className={styles.leftSection}>
            <input 
              type="checkbox" 
              checked={getSelectAllStatus() === true}
              ref={(input) => {
                if (input) {
                  input.indeterminate = getSelectAllStatus() === 'indeterminate';
                }
              }}
              onChange={toggleSelectAll}
              className={styles.checkbox} 
            />
            <span className={styles.selectAll}>
              全选
              {cartItems.length > 0 && (
                <span className={styles.selectedCount}>
                  ({selectedCount()}/{cartItems.length})
                </span>
              )}
            </span>
          </div>
          
          {isEditMode ? (
            <button 
              className={styles.deleteBtn}
              onClick={deleteSelected}
            >
              删除
            </button>
          ) : (
            <div className={styles.rightSection}>
              <div className={styles.priceInfo}>
                <span className={styles.total}>总计: ¥{calculateTotal().toFixed(2)}</span>
                <span className={styles.save}>为你节省: ¥{calculateSaved().toFixed(2)}</span>
              </div>
              <button 
                className={styles.submitBtn}
                onClick={goToCheckout}
              >
                去下单({selectedCount()})
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}